from django.contrib.auth.hashers import make_password
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.views import auth_login, auth_logout, login_required
from django.urls import reverse

from main.models import Category, Tag, Course
from .forms import LoginForm, RegisterForm, CenterForm, UpdatePasswordForm
from .models import MyUser,WeiBoUser
import requests


# Create your views here.
def login(request):
    # 参数是导入POST请求的表单数据，用于输入错误信息时不会把全部信息清空
    forms = LoginForm()

    errors = None
    if request.method == "POST":
        forms = LoginForm(request.POST)

        username = request.POST.get("username")
        password = request.POST.get("password")
        # 结果是多集合   通过用户名找到用户对象
        user = MyUser.objects.filter(username=username).first()
        # 账号存在
        if user:
            # 判断密码是否正确
            if user.check_password(password):
                # 将用户数据同步登录至前台
                auth_login(request, user)
                # 获取next（重定向）
                # next_url = request.GET.get("next")
                # if next_url:
                #     print(next_url)
                #     return redirect(to=next_url)
                # else:
                #     # 重定向到首页
                return redirect(to="/")
            else:
                errors = "密码错误"
        else:
            errors = "用户名不存在"
    return render(request, "user/login.html", context=({"errors": errors, "forms": forms}))


def register(request):
    # 参数是导入POST请求的表单数据，用于输入错误信息时不会把全部信息清空
    forms = RegisterForm()
    if request.method == "POST":
        forms = RegisterForm(request.POST)
        # 表单填写数据是否有效
        if forms.is_valid():
            # 只会判断数据模型中的数据和格式，因此不会判断密码是否一致，需要我们自己判断
            # 为了保持与模板数据一致，删除password2
            password = forms.cleaned_data.get("password")
            password2 = forms.cleaned_data.pop("password2")
            if password != password2:
                # 返回错误信息，forms.errors.update()
                forms.errors.update({
                    "password": ["密码不一致"]
                })
            else:
                # 获取对象，但是不提交数据库，因为此时的密码还没有被加密
                user = forms.save(commit=False)
                # 加密密码
                user.password = make_password(password)
                # 保存数据库
                forms.save()
                # 同步前台用户
                auth_login(request, user)
                return redirect(to="/")

    return render(request, "user/register.html", context=({"forms": forms}))


@login_required
def center(request):
    # 传入当前初始用户数据,个人信息
    forms = CenterForm(initial={
        "username": request.user.username,
        "email": request.user.email,
        "phone": request.user.phone,
        "last_name": request.user.last_name,
        "first_name": request.user.first_name,
        "last_login": request.user.last_login,
        "date_joined": request.user.date_joined,
    })

    if request.method == "POST":
        # data 负责表单传入的数据   instance负责原始数据，确保在修改时，不会出现因重复用户名等错误
        forms = CenterForm(data=request.POST, files=request.FILES, instance=request.user, )

        if forms.is_valid():
            forms.save()
            return redirect("/")

    return render(request, "user/center.html", context={
        "forms": forms,

    })


def update_password(request):
    # print(request.user,"++++++++++++++++++++++++++++++++++")
    # print(dir(request.user),"++++++++++++++++++++++++++++++++++")
    forms = UpdatePasswordForm()
    if request.method == "POST":
        # 保留表单正确数据，保证在提交错误时不会清空
        forms = UpdatePasswordForm(request.POST)
        if forms.is_valid():
            old_password = forms.cleaned_data.get("old_password")
            new_password = forms.cleaned_data.pop("new_password")
            new_password_replace = forms.cleaned_data.pop("new_password_replace")
            if not request.user.check_password(old_password):
                forms.errors.update({
                    "old_password": ["旧密码错误"]
                })
            else:
                if new_password == new_password_replace:
                    request.user.set_password(new_password)
                    auth_logout(request)
                    return redirect(to="/user/login")
                else:
                    forms.errors.update({
                        "old_password": ["新密码不一致"]
                    })
    return render(request, "user/update_password.html", context=({"forms": forms}))


def message(request):
    return render(request, "user/message.html")


def logout(request):
    categorys = Category.objects.all()
    tags = Tag.objects.all()
    courses = Course.objects.all()
    courses_fire = Course.objects.filter(fire=True)[:6]  # 只获取前6个符合条件的课程
    request.session.flush()
    return render(request, "main/index.html", context={
        "categorys": categorys,
        "tags": tags,
        "courses": courses,
        "courses_fire": courses_fire
    })


# 微博登录接口
def auth(request):
    # 获取接口1请求获得的code，网址参数，每次都在变化
    code = request.GET.get("code")
    # 作为接口2post请求的请求数据
    data = {
        "client_id": "1121631288",
        "client_secret": "dfc8cbb9b80461c0024d5a4f846c81b7",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/user/auth/"
    }
    res = requests.post("https://api.weibo.com/oauth2/access_token", data=data)
    print(res.json(),"===============")
    uid = res.json().get("uid")
    user = WeiBoUser.objects.filter(wei_bo_user=uid).first()
    if user:
        http_user = user.http_user
        auth_login(request, http_user)
    else:
        http_user = MyUser.objects.create_user(username=f"微博用户_{uid}",password="123456")
        wei_bo_user = WeiBoUser()
        wei_bo_user.wei_bo_user = uid
        wei_bo_user.http_user = http_user
        wei_bo_user.save()
        auth_login(request, http_user)
    return redirect(to=reverse("main:index"))



def check_username(request):
    username = request.GET.get("username")
    user = MyUser.objects.filter(username=username).first()
    if user:
        return JsonResponse({
            "code":0,
            "msg":"不可用"
        })
    else:
        return JsonResponse({
            "code": 1,
            "msg": "可用"
        })